package cuiyt.juc.condition;

import java.util.UUID;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author cyt
 * @describe
 * @create 2020-12-24 16:32
 */
public class ConditionTest {
    final Lock lock = new ReentrantLock();
    /**
     * condition 依赖于 lock 来产生
     */
    final Condition notFull = lock.newCondition();
    final Condition notEmpty = lock.newCondition();
    final Object[] items = new Object[100];
    int putptr;
    int takeptr;
    int count;

    /**
     * 生产
     *
     * @param x
     * @throws InterruptedException
     */
    public void put(Object x) throws InterruptedException {

        lock.lock();
        try {
            System.out.println("put - > " + x);
            while (count == items.length) {
                notFull.await();  // 队列已满，等待，直到 not full 才能继续生产
            }
            items[putptr] = x;
            if (++putptr == items.length) {
                putptr = 0;
            }
            ++count;
            notEmpty.signal(); // 生产成功，队列已经 not empty 了，发个通知出去
        } finally {
            lock.unlock();
        }
    }

    /**
     * 消费
     *
     * @return
     * @throws InterruptedException
     */
    public Object take() throws InterruptedException {
        lock.lock();
        try {
            while (count == 0) {
                notEmpty.await(); // 队列为空，等待，直到队列 not empty，才能继续消费
            }
            Object x = items[takeptr];
            if (++takeptr == items.length) {
                takeptr = 0;
            }
            --count;
            notFull.signal(); // 被我消费掉一个，队列 not full 了，发个通知出去
            return x;
        } finally {
            lock.unlock();
        }
    }

    public static void main(String[] args) {
        ConditionTest conditionTest = new ConditionTest();
        for (int i = 0; i < 5; i++) {
            new Thread(() -> {
                try {
                    conditionTest.put(UUID.randomUUID().toString());
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }, "A").start();
        }
        for (int i = 0; i < 5; i++) {
            new Thread(() -> {
                try {
                    System.out.println("take - > " + conditionTest.take());
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }, "A").start();
        }
    }
}
